package com.sanjishu.enterlab.electricity.sale.service;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.domain.Admin;
import com.sanjishu.enterlab.electricity.sale.domain.User;
import com.sanjishu.enterlab.electricity.sale.mapper.AdminMapper;
import com.sanjishu.enterlab.electricity.sale.mapper.UserMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;

    public User findByPhone(String phone) {
        return userMapper.findByPhone(phone);
    }

    public User insert(String phone, String password, String saler, Integer types, String name){
        Admin admin = adminMapper.findByPhoneOrName(saler);
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        if (admin != null) {
            user.setAdminId(admin.getId());
        }
        user.setTypes(types);
        user.setName(name);
        user.setStatus(User.STATUS_NORMAL);
        userMapper.insert(user);
        return user;
    }

    public Response updatePassword(String phone, String password) {
        User user = userMapper.findByPhone(phone);
        return newPassword(user, password);
    }

    public List<User> findSales() {
        return userMapper.findSales();
    }

    public Response modifyPassword(Integer userId, String password) {
        User user = userMapper.selectByPrimaryKey(userId);
        return newPassword(user, password);
    }

    public Response newPassword(User user, String password) {
        if (user != null) {
            user.setPassword(DigestUtils.md5Hex(password));
            userMapper.updateByPrimaryKey(user);
            return Response.buildSuccess("密码修改成功。");
        } else {
            return Response.getError("密码修改失败，请重新尝试。");
        }
    }

    public void deleteSale(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setStatus(User.STATUS_DELETED);
        userMapper.updateByPrimaryKey(user);
    }

}
